<template>
  <!-- 主地图容器 -->
  <div id="map" class="map-container">
    <!-- 测量子组件 - 定位在左上角 -->
    <div class="measurement-container">
      <MeasureTool v-if="map" :map="map"/>
    </div>

    <!-- 地图控制面板 -->
    <div class="map-controls">

      <!-- 控制按钮组：缩放、复位、旋转 -->
      <div class="control-group">
        <button @click="zoomIn" title="放大">+</button>
        <button @click="zoomOut" title="缩小">-</button>
        <button @click="resetView" title="复位">↺</button>
        <button @click="toggleRotation" title="旋转">
          {{ rotationEnabled ? '锁定' : '旋转' }}
        </button>
      </div>

      <!-- 鼠标位置显示 -->
      <div class="control-group">
        <div class="mouse-position">
          <span>经度: {{ mousePosition.lon || '--' }}</span>
          <span>纬度: {{ mousePosition.lat || '--' }}</span>
        </div>
      </div>

      <!-- 比例尺显示 -->
      <div class="control-group">
        <div class="scale-control">比例尺: 1:{{ currentScale }}</div>
      </div>

      <!-- 图层控制面板 -->
      <div class="control-group layer-control">
        <h4>图层控制</h4>
        <label>
          <input type="checkbox" v-model="layers.vector.visible" @change="toggleLayer('vector')"/>
          天地图矢量
        </label>

        <label>
          <input type="checkbox" v-model="layers.annotation.visible" @change="toggleLayer('annotation')"/>
          天地图注记
        </label>

        <label>
          <input type="checkbox" v-model="layers.wms.visible" @change="toggleLayer('wms')"/>
          GeoServer WMS
        </label>

        <label>
          <input type="checkbox" v-model="layers.test.visible" @change="toggleLayer('test')"/>
          国家边界线
        </label>

        <div v-if="layers.wms.visible" class="opacity-control">
          <span>透明度:</span>
          <input
              type="range"
              min="0"
              max="100"
              v-model="layers.wms.opacity"
              @input="updateLayerOpacity('wms')"
          />
          <span>{{ layers.wms.opacity }}%</span>
        </div>
      </div>
    </div>
  </div>

  <NavigationBar/>
</template>

<script setup>
import { onMounted, nextTick, ref, reactive } from 'vue'    // 导入 Vue 相关功能
import { Map, View } from 'ol'                              // 从 OpenLayers 库导入核心类：Map 和 View
import TileLayer from 'ol/layer/Tile'                       // 瓦片图层
import TileWMS from 'ol/source/TileWMS'                     // WMS 瓦片数据源
import XYZ from 'ol/source/XYZ'                             // XYZ 格式瓦片源（如天地图）
import { toStringXY } from 'ol/coordinate'                  // 坐标格式化工具
import 'ol/ol.css'                                          // OpenLayers 默认样式
import MeasureTool from './MeasurementControler/MeasurementControls.vue' // 根据实际路径调整
import {
  defaults as defaultControls,
  Zoom,
  Rotate,
  ScaleLine,
  MousePosition,
  OverviewMap,
} from 'ol/control'     // 各种地图控件
import {
  defaults as defaultInteractions,
  DragPan,
  MouseWheelZoom,
  PinchZoom,
  KeyboardPan,
  KeyboardZoom,
} from 'ol/interaction'
import NavigationBar from "./NavigationBar.vue"; // 地图交互行为


// ==================== 天地图服务 URL 配置 ====================
// 使用 WMTS 协议加载天地图矢量底图（含密钥）
const tiandituVecUrl = 'http://t0.tianditu.gov.cn/vec_w/wmts?tk=e0544d1d5d87cd63d1f2d0338830974c&layer=vec&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}'

// 天地图注记图层（文字标注）
const tiandituCvaUrl = 'http://t0.tianditu.gov.cn/cva_w/wmts?tk=e0544d1d5d87cd63d1f2d0338830974c&layer=cva&style=default&tilematrixset=w&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}'


// ==================== 响应式状态管理 ====================
// 管理各图层的显示状态、透明度和对应的 OL 图层对象
const layers = reactive({
  vector: { visible: true, layer: null },
  annotation: { visible: true, layer: null },
  wms: { visible: true, opacity: 100, layer: null },
  test: { visible: true, opacity: 80, layer: null },
})

// 鼠标当前位置（经度、纬度）
const mousePosition = reactive({
  lon: '',
  lat: '',
})

// 当前地图比例尺
const currentScale = ref('--')

// 是否启用地图旋转功能
const rotationEnabled = ref(false)

// 地图实例和鹰眼控件的引用
let map = ref(null)
let overviewMapControl = null


// ==================== 图层创建函数 ====================
// 创建天地图矢量图层
const createTiandituVecLayer = () => {
  const layer = new TileLayer({
    source: new XYZ({
      url: tiandituVecUrl,
      tileSize: 256,
      crossOrigin: 'anonymous',
      SRS: 'EPSG:4326',
      CRS: 'EPSG:4326',
    }),
    visible: layers.vector.visible,
    zIndex: 0, // 图层堆叠顺序
  })
  layers.vector.layer = layer // 保存图层引用
  return layer
}

// 创建天地图注记图层
const createTiandituCvaLayer = () => {
  const layer = new TileLayer({
    source: new XYZ({
      url: tiandituCvaUrl,
      tileSize: 256,
      crossOrigin: 'anonymous',
      SRS: 'EPSG:4326',
      CRS: 'EPSG:4326',
    }),
    visible: layers.annotation.visible,
    zIndex: 1,
  })
  layers.annotation.layer = layer
  return layer
}

// 创建连接到 GeoServer 的 WMS 图层（城市数据）
const createGeoserverLayer = () => {
  const layer = new TileLayer({
    name: '中国各城市',
    source: new TileWMS({
      url: '/geoserver/first_homework/wms',    // 本地代理路径       ***********************************************************************************************
      params: {
        VERSION: '1.1.0',
        LAYERS: 'first_homework:cities1',      // 图层名称          ***********************************************************************************************
        FORMAT: 'image/png',                   // 返回图像格式
        TRANSPARENT: true,                     // 背景透明
        SRS: 'EPSG:4326',                      // 坐标系统（WGS84）
        // 'SRS': 'EPSG:3857',                 // 或尝试 Web Mercator
        // 'SRS': 'EPSG:4490',                 // 或尝试中国大地2000
        TILED: true,                           // 启用瓦片模式
        STYLES: '',                            // 不使用特定样式
      },
      serverType: 'geoserver',                 // 服务器类型
      crossOrigin: 'anonymous',                // 跨域设置
      wrapX: false,                            // 禁止水平重复
    }),
    visible: layers.wms.visible,
    opacity: layers.wms.opacity / 100,         // 设置透明度（0-1）
    zIndex: 2,
  })
  layers.wms.layer = layer
  return layer
}

// 创建另一个 WMS 图层：国家边界（来自 ne 命名空间）
const createGeoserverLayer1 = () => {
  const layer = new TileLayer({
    name: '全球国家',
    source: new TileWMS({
      url: '/geoserver/ne/wms',
      params: {
        VERSION: '1.1.0',
        LAYERS: 'ne:countries',
        FORMAT: 'image/png',
        TRANSPARENT: true,
        SRS: 'EPSG:4326',
        TILED: true,
        STYLES: '',
      },
      serverType: 'geoserver',
      crossOrigin: 'anonymous',
      wrapX: false,
    }),
    visible: layers.test.visible,
    opacity: layers.test.opacity / 100,
    zIndex: 2,
  })
  layers.test.layer = layer
  return layer
}

// ==================== 图层控制方法 ====================
// 切换指定图层的可见性
const toggleLayer = (layerType) => {
  if (layers[layerType].layer) {
    layers[layerType].layer.setVisible(layers[layerType].visible)
  }
}

// 更新图层透明度
const updateLayerOpacity = (layerType) => {
  if (layers[layerType].layer) {
    layers[layerType].layer.setOpacity(layers[layerType].opacity / 100)
  }
}

// ==================== 地图操作方法 ====================
// 放大一级缩放级别
const zoomIn = () => {
  const view = map.getView()
  const zoom = view.getZoom()
  view.setZoom(zoom + 1)
}

// 缩小一级缩放级别
const zoomOut = () => {
  const view = map.getView()
  const zoom = view.getZoom()
  view.setZoom(zoom - 1)
}

// 重置视图为初始状态（中心、缩放、旋转）
const resetView = () => {
  const view = map.getView()
  view.setCenter([116.397428, 39.90923])
  view.setZoom(4)
  view.setRotation(0)
  rotationEnabled.value = false
}

// 切换地图旋转功能
const toggleRotation = () => {
  rotationEnabled.value = !rotationEnabled.value
  const interactions = map.getInteractions()
  interactions.getArray().forEach((interaction) => {
    if (interaction instanceof DragPan) {
      interaction.set('constrainRotation', rotationEnabled.value ? 0 : false) // 限制旋转角度或关闭限制
    }
  })
}

// ==================== 地图初始化 ====================
// 初始化 OpenLayers 地图
const initMap = async () => {
  await nextTick()

  const mapContainer = document.getElementById('map')
  if (!mapContainer) {
    console.error('Map container not found')
    return
  }

  // 修复容器尺寸为 0 的问题（常见于 Vue 异步渲染）
  if (mapContainer.offsetWidth === 0 || mapContainer.offsetHeight === 0) {
    mapContainer.style.height = 'calc(100vh - 60px)'
    await new Promise((resolve) => setTimeout(resolve, 50))
  }

  // 创建自定义控件 ====================
  const zoomControl = new Zoom()
  const rotateControl = new Rotate()
  const scaleControl = new ScaleLine({
    units: 'metric',
    bar: true,
    steps: 4,
    text: true,
    minWidth: 100,
  })

  const mousePositionControl = new MousePosition({
    coordinateFormat: (coord) => {
      if (!coord || coord.length < 2) {
        return '--';
      }
      const [x, y] = coord;

      // 转换为数字并格式化
      const lon = Number(x)?.toFixed(6) ?? '--';
      const lat = Number(y)?.toFixed(6) ?? '--';

      mousePosition.lon = lon;
      mousePosition.lat = lat;

      return toStringXY(coord, 6);
    },
    projection: 'EPSG:4326',
    className: 'custom-mouse-position',
  });

  // 鹰眼地图（OverviewMap）控件
  overviewMapControl = new OverviewMap({
    className: 'ol-overviewmap',
    layers: [
      new TileLayer({
        source: new XYZ({
          url: tiandituVecUrl,
          tileSize: 256,
          crossOrigin: 'anonymous',
        }),
      }),
    ],
    collapseLabel: '\u00BB',  // 折叠时显示的字符
    label: '\u00AB',          // 展开时显示的字符
    collapsed: false,
  })

  // 创建地图实例 ====================
  map.value = new Map({
    target: 'map',
    layers: [
      createTiandituVecLayer(), // 底图
      createTiandituCvaLayer(), // 标注
      createGeoserverLayer(),   // WMS图层（城市）
      createGeoserverLayer1(),  // 国家边界
    ],
    view: new View({
      // 想看“全球视图” → 用 center: [0,0], zoom: 2
      // 想看“中国视图” → 用 center: [116.39, 39.90], zoom: 4
      // center: [0, 0],                // 初始中心点（全球居中）
      // zoom: 2,
      center: [116.397428, 39.90923],
      zoom: 4,
      projection: 'EPSG:4326',       // 使用 WGS84 地理坐标系
      extent: [-180, -90, 180, 90],  // WGS84 全球范围
    }),


    controls: defaultControls().extend([
      zoomControl,
      rotateControl,
      scaleControl,
      mousePositionControl,
      overviewMapControl, // 将鹰眼控件添加到地图
    ]),
    interactions: defaultInteractions().extend([
      new DragPan({ constrainRotation: false }), // 拖拽平移
      new MouseWheelZoom(),                            // 鼠标滚轮缩放
      new PinchZoom(),                                 // 触摸缩放
      new KeyboardPan(),                               // 键盘方向键平移
      new KeyboardZoom(),                              // 键盘 +/- 缩放
    ]),
  })

  // 监听分辨率变化以更新比例尺
  map.getView().on('change:resolution', () => {
    const resolution = map.getView().getResolution()
    const units = map.getView().getProjection().getUnits()
    const dpi = 25.4 / 0.28                        // 标准 DPI
    const mpu = units === 'degrees' ? 111320 : 1   // 每单位米数
    const scale = Math.round(resolution * mpu * dpi * 39.37);
    currentScale.value = scale.toString(); // 或者 `${scale}`
  })

  // 监听地图容器尺寸变化
  map.on('change:size', () => {
    map.updateSize()
  })

  // 强制更新地图尺寸（防止首次加载时空白）
  setTimeout(() => {
    map.updateSize()
  }, 100)
}

// ==================== 组件挂载后执行 ====================
onMounted(() => {
  setTimeout(initMap, 100)  // 延迟初始化地图，确保 DOM 稳定
})

</script>


<style scoped>
.map-container {
  position: absolute;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f5f5f5;
}

.map-controls {
  position: absolute;
  top: 30px;
  right: 30px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  max-width: 250px;
}

.control-group {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.control-group:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.control-group button {
  margin: 0 5px 5px 0;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #f8f9fa;
  cursor: pointer;
  font-weight: bold;
}

.control-group button:hover {
  background: #e9ecef;
}

.mouse-position {
  font-size: 12px;
  display: flex;
  flex-direction: column;
}

.mouse-position span {
  margin-bottom: 3px;
}

.scale-control {
  font-size: 12px;
  font-weight: bold;
  color: #333;
}

.layer-control h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #333;
}

.layer-control label {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-left: 22%;
  margin-bottom: 8px;
  font-size: 13px;
  cursor: pointer;
}

.opacity-control {
  margin-top: 8px;
  display: flex;
  align-items: center;
  font-size: 12px;
}

.opacity-control input {
  margin: 0 8px;
  width: 80px;
}

:deep(.custom-mouse-position) {
  position: absolute;
  bottom: 8px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(255, 255, 255, 0.8);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  border: 1px solid #ccc;
}

/* 鹰眼地图样式 */
:deep(.ol-overviewmap) {
  bottom: 10px !important;
  left: auto !important;
  right: 10px !important;
  top: auto !important;
}

:deep(.ol-overviewmap .ol-overviewmap-map) {
  border: 1px solid #999;
  height: 150px;
  width: 200px;
}

:deep(.ol-overviewmap:not(.ol-collapsed)) {
  border: 2px solid #ccc;
  border-radius: 4px;
  background: white;
}

:deep(.ol-overviewmap .ol-overviewmap-box) {
  border: 2px solid rgba(0, 60, 136, 0.5);
}

.measurement-container {
  position: absolute;
  left: 15px;
  top: 70px;
  z-index: 1000;
}

:deep(.measure-tool) {
  position: relative;
  left: auto;
  top: auto;
}

</style>